<?php
/* 登录 */
namespace Api\Controller;
use Think\Controller;
//use Think\Log;
class PActivityController extends Controller {

 	
	public function __construct()
	{
		//解决跨域
		echoHeader();
	}

	public function index()
	{
		$map['is_deleted'] = 0;
		$map['status'] = 1;
		$act = M("PActivity")->where($map)->field('id,name,url,description')
			->order('id desc')->find();

		if ($act) {
			$act['description'] = htmlspecialchars_decode($act['description']);
			$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$act));
		}else{
			$this->ajaxReturn(array('err_code'=>10001, 'err_msg'=>'暂时没有活动'));
		}
	}


	public function addScore()
	{
		$userId = I('post.user_id', 0, 'intval');
		$actId = I('post.act_id', 0, 'intval');

		$map['is_deleted'] = 0;
		$map['status'] = 1;
		$map['id'] = $actId;

		$act = M("PActivity")->where($map)->find();
		if (!$act) {
			$this->ajaxReturn(array('err_code'=>10001, 'err_msg'=>'暂时没有活动'));
		}

		$userMap['id'] = $userId;
		$userMap['is_deleted'] = 0;
		$user = M("PUser")->where($userMap)->find();
		if (!$user) {
			$this->ajaxReturn(array('err_code'=>10002, 'err_msg'=>'用户不存在'));
		}



		$scoreMap['is_deleted'] = 0;
		$scoreMap['user_id'] = $user['id'];
		$scoreMap['type'] = 5;
		$scoreMap['act_id'] = $act['id'];
		$scoreMap['score'] = array('gt', 0);
		$sum = M("PScoreRecord")->where($scoreMap)->sum('score');

		if ($sum > $act['limit_score']) {
			$this->ajaxReturn(array('err_code'=>10003, 'err_msg'=>'转发积分已封顶'));
		}

		$score = $act['share_score'];
		if ( ($act['limit_score'] - $sum) < $score) {
			$score = $act['limit_score'] - $sum;
		}

        $expire=M('PConfig')->where('key','=','task_expire')->find();


        M()->startTrans();
		$updateUser = M("PUser")->where($userMap)->setInc('score', $score);
		if (!$updateUser) {
			M()->rollback();
			$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'更新积分失败'));
		}
		$scoreMap['score'] = $score;
		$scoreMap['add_time'] = time();
        $scoreMap['consume'] = $score;
        $scoreMap['expire_time']=time()+$expire['value']*3600*24;

        $insert = M("PScoreRecord")->add($scoreMap);
		if ($insert) {
			M()->commit();
			$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'积分更新成功'));
		}else{
			M()->rollback();
			$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'更新积分失败'));
		}
	}

	
}